"use client";
import React, { useState , useEffect, useRef } from "react";
import { useForm } from "react-hook-form";
import FormItem from "@/components/formItem";
import styles from "./index.module.scss";
import { getLocalStorage } from "@/utils/localStorage";

interface UserInfoProps{
  [key: string] : any
}
interface HeaderProps {
  className?: string;
  title: string;
  onClose: () => void;
}

const Header: React.FC<HeaderProps> = ({ className = "", title, onClose }) => {
  return (
    <div className={`${styles["header-component"]} ${className}`}>
      <div className={`${styles["header-title"]}`}>{title}</div>
      <div className={`${styles["header-close"]}`}>
        <i className="fa fa-solid fa-close" onClick={() => onClose()}></i>
      </div>
    </div>
  );
};

interface FoolterProps {
  className?: string;
  onCancel: () => void;
  onOk: () => void;
}
const Foolter: React.FC<FoolterProps> = ({
  className = "",
  onCancel,
  onOk,
}) => {
  return (
    <div className={`${styles["foolter-component"]} ${className}`}>
      <div className={`${styles["foolter-content"]}`}>
        <div
          className={`${styles["foolterCancel"]}`}
          onClick={() => onCancel()}
        >
          取消
        </div>
        <div className={`${styles["foolterOK"]}`} onClick={() => onOk()}>
          确定
        </div>
      </div>
    </div>
  );
};

interface EditUserProps {
  className?: string;
  onClose: () => void;
  title: string;
  getFormData: (data:any) => void
}




const EditUser: React.FC<EditUserProps> = ({
  className = "",
  onClose,
  title,
  getFormData
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    control,
  } = useForm();


  const [userInfo, setUserInfo] = useState<UserInfoProps>({});
  useEffect(() => {
    try {
      const _USER : string | null= getLocalStorage('userInfo')
      const str_user = _USER ? JSON.parse(_USER) : {};

      const user = str_user ? JSON.parse(str_user) : {};
      setUserInfo(user);
    } catch (error) {
      console.log(error);
    }
  }, []);



  const buttonRef = useRef<any>(null);

  const onSubmit = handleSubmit(async (formData:any) => {
    const postData = {
        ...formData,
        nickname: formData?.nickname || userInfo?.nickname,
        email: formData?.email || userInfo?.email,
        phone: formData?.phone || userInfo?.phone,
        carNumber: formData?.carNumber || userInfo?.carNumber,
        signature: formData?.signature || userInfo?.signature,
    }
    getFormData(postData)
    console.log("data--->", postData);
  });

  const onOk = () => {
     // 判断按钮引用是否存在，以及按钮是否存在
     if (buttonRef.current && buttonRef.current?.click) {
        // 调用按钮的点击事件
        buttonRef.current.click();
      }
  };

  const onChangeNickName = (e:any) => {
    console.log(e.target.value)
  }

  return (
    <div className={`${styles["edit-user-component"]} ${className}`}>
      <div className={`${styles["header"]}`}>
        <Header title={title} onClose={() => onClose()} />
      </div>

      <div className={`${styles['edit-user-body']}`}>
        <form onSubmit={onSubmit} className={`${styles["edituser-form"]}`}>
          <FormItem
            label="用户昵称"
            name="nickname"
            className={`${styles["custom-base-item"]}`}
            customFormItemLabel={`${styles["customFormItemLabel"]}`}
            errors={errors}
          >
            <input
              className={`${styles["base-input"]}`}
              id="nickname"
              placeholder="请输入用户昵称"
              defaultValue={userInfo?.nickname ? userInfo?.nickname : ''}
              {...register("nickname", {
                required: "请输入用户昵称",
                //   pattern: {
                //     value: /^[^\u4e00-\u9fa5]{1,}$/, // 这个正则是匹配除中文外任何字符
                //     message:"登录名不能用中文"
                //   }
              })}
            />
          </FormItem>

          <FormItem
            label="邮箱"
            name="email"
            className={`${styles["custom-base-item"]}`}
            customFormItemLabel={`${styles["customFormItemLabel"]}`}
            errors={errors}
          >
            <input
              className={`${styles["base-input"]}`}
              id="email"
              defaultValue={userInfo?.email ? userInfo?.email : ''}
              placeholder="请输入邮箱"
              {...register("email", {
                required: "请输入邮箱",
                pattern: {
                  value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, // 这个正则是匹配除中文外任何字符
                  message: "请输入正确的邮箱",
                },
              })}
            />
          </FormItem>

          <FormItem
            label="手机号"
            name="phone"
            className={`${styles["custom-base-item"]}`}
            customFormItemLabel={`${styles["customFormItemLabel"]}`}
            errors={errors}
          >
            <input
              defaultValue={userInfo?.phone ? userInfo?.phone : ''}
              className={`${styles["base-input"]}`}
              id="phone"
              placeholder="请输入手机号"
              {...register("phone", {
                required: "请输入手机号",
                pattern: {
                  value: /^1[3456789]\d{9}$/,
                  message: "请输入正确的手机号",
                },
              })}
            />
          </FormItem>

          <FormItem label="车牌号" name="carNumber" className={`${styles["custom-base-item"]}`}  customFormItemLabel={`${styles["customFormItemLabel"]}`}  errors={errors}>
            <input
              defaultValue={userInfo?.carNumber ? userInfo?.carNumber : ''}
              className={`${styles["base-input"]}`}
              id="carNumber"
              placeholder="工信部要求司机提供车牌号"
              {...register("carNumber", {
                pattern: {
                  value: /[\u4e00-\u9fa5][A-Z][A-Z0-9]{5}/gi,
                  message: "请输入正确的车牌号",
                },
              })}
            />
          </FormItem>

          <FormItem
            label="个性签名"
            name="signature"
            className={`${styles["custom-base-item"]}`}
            customFormItemLabel={`${styles["customFormItemLabel"]}`}
            errors={errors}
          >
            <textarea
               defaultValue={userInfo?.signature ? userInfo?.signature : ''}
              rows={5}
              className={`${styles["base-input"]} ${styles['signature-textarea']}`}
              id="signature"
              placeholder="请输入个性签名"
              {...register("signature", {
                pattern: {
                  value: /^.{0,150}$/,
                  message: "个性签名不能超过150字",
                },
              })}
            />
          </FormItem>

          <button type="submit" className={`${styles["onSubmit-btn"]}`} ref={buttonRef} style={{ display: 'none' }}>
            提交
          </button>
        </form>
      </div>

      <div className={`${styles["foolter"]}`}>
        <Foolter onCancel={() => onClose()} onOk={() => onOk()} />
      </div>
    </div>
  );
};

export default EditUser;
